package com.dennis.client;

import com.dennis.jedis.RedisPool;
import io.netty.util.concurrent.DefaultThreadFactory;
import redis.clients.jedis.Jedis;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.LongAdder;
import java.util.stream.IntStream;

/**
 * @author Dennis Li
 * @date 2020/8/19 15:09
 */
public class SocketClient {

    private static int count = 0;

    public static final int nums = 10;

    public static void count(String name, String host, int port) {
        try (Socket socket = new Socket(host, port);
             InputStream is = socket.getInputStream();
             OutputStream os = socket.getOutputStream()) {
            while (true) {
                count++;
                os.write((name + host).getBytes());
                is.read(new byte[1024]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void client(String name, String host, int port) {
        try (Socket socket = new Socket(host, port);
             InputStream is = socket.getInputStream();
             OutputStream os = socket.getOutputStream()) {
            while (true) {
                os.write((name + host).getBytes());
                is.read(new byte[1024]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        final int[] ports = IntStream.range(6001, 6000 + nums).toArray();
        final ExecutorService pool = Executors.newFixedThreadPool(nums);

        pool.submit(() -> count("count", "localhost", 6000));
        for (int port : ports) {
            pool.submit(() -> client("client-" + port, "localhost", port));
        }

        final Jedis redis = RedisPool.pool.getResource();
        redis.select(5);
        for (int i = 0; i < 3000; i++) {
            Thread.sleep(100);
            // 小写代表没有模拟延迟
            redis.set("normal:" + nums + ":" + i, Integer.toString(count));
        }
    }

}
